package com.zjcode.cdcer.controller;

import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.component.commons.controller.BaseController;
import com.chinatechstar.component.commons.supports.PageData;
import com.chinatechstar.component.commons.utils.SequenceGenerator;
import com.chinatechstar.component.commons.utils.UuidUtil;
import com.zjcode.cdcer.mapper.SysRoleMapper;
import com.zjcode.cdcer.mapper.SysUserMapper;
import com.zjcode.cdcer.model.CerCasUsersyncinfo;
import com.zjcode.cdcer.model.SysUser;
import com.zjcode.cdcer.model.TkmSysEx;
import com.zjcode.cdcer.model.ZjcodeSysUserTmp;
import com.zjcode.cdcer.model.basic.JsonObj;
import com.zjcode.cdcer.service.CerCasUsersyncinfoService;
import com.zjcode.cdcer.service.TkmSysExService;
import com.zjcode.cdcer.service.ZjcodeSysUserTmpService;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName:CerDwsUserController
 * @功能：
 * @author：wlei
 * @日期：2023/2/7-02:38
 **/
@RestController
@Slf4j
@RequestMapping("/v1/dwsuser/")
public class CerDwsUserController extends BaseController {

    private static SequenceGenerator sequenceGenerator = new SequenceGenerator();

    @Autowired
    private ZjcodeSysUserTmpService zjcodeSysUserTmpService;
    @Autowired
    private TkmSysExService tkmSysExService;
    @Autowired
    private CerCasUsersyncinfoService cerCasUsersyncinfoService;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 按照id查询临时用户
     *
     * @return
     */
    @PostMapping("findById")
    public JsonObj findById(@RequestBody PageData pageData) {
        String id = (String) pageData.get("id");
        ZjcodeSysUserTmp record = zjcodeSysUserTmpService.findById(id);
        Map<String, Object> result = new HashMap<>();
        result.put("record", record);
        return JsonObj.success(result);
    }

    /**
     * 新增用户
     *
     * @return
     */
    @PostMapping("addSysUser")
    public JsonObj addSysUser(@RequestBody PageData pageData) {
        String data = (String) pageData.get("data");
        ZjcodeSysUserTmp record = JSONObject.parseObject(data, ZjcodeSysUserTmp.class);
        ZjcodeSysUserTmp byId = zjcodeSysUserTmpService.findById(record.getId());
        if (Objects.isNull(byId)) {
            // 用户不存在,执行新增操作
            zjcodeSysUserTmpService.insertSysUser(record);
        } else {
            // 用户存在,执行更新操作
            zjcodeSysUserTmpService.updateSysUser(record);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("id", record.getId());
        return JsonObj.success(result);
    }

    /**
     * 同步临时用户到系统用户
     *
     * @param pageData
     * @return
     */
    @PostMapping("syncTmpUserToSysUser")
    public JsonObj syncTmpUserToSysUser(@RequestBody PageData pageData) {
        String data = (String) pageData.get("data");
        ZjcodeSysUserTmp record = JSONObject.parseObject(data, ZjcodeSysUserTmp.class);
        ZjcodeSysUserTmp byId = zjcodeSysUserTmpService.findById(record.getId());
        // 1.先完成临时库中的数据操作
        if (Objects.isNull(byId)) {
            // 用户不存在,执行新增操作
            zjcodeSysUserTmpService.insertSysUser(record);
        } else {
            // 用户存在,执行更新操作
            zjcodeSysUserTmpService.updateSysUser(record);
        }
        // 重新取出临时库中的数据
        byId = zjcodeSysUserTmpService.findById(record.getId());
        // 将数据写入正式库
        // 构造SysUser
        long userId = sequenceGenerator.nextId();
        SysUser sysUser = getSysUser(byId, userId);
        // 写入正式库
        sysUserMapper.insert(sysUser);
        // 写入权限
        String roleId = byId.getRoleId();
        if (!Objects.isNull(roleId)) {
            sysRoleMapper.insertSysRoleUser(sequenceGenerator.nextId(),
                                            Long.valueOf(roleId),
                                            userId);
        }

        // 像扩展信息表（），中加入数据
        TkmSysEx sysEx = new TkmSysEx();
        sysEx.setId(UuidUtil.get32UUID());
        sysEx.setBillNo(sysUser.getPassword());
        sysEx.setSourceId(sysUser
                              .getId()
                              .toString());
        sysEx.setCreateDatetime(new Date(System.currentTimeMillis()));
        tkmSysExService.insert(sysEx);

        // 更新cas表中的数据,表示数据已经同步到正式库中
        CerCasUsersyncinfo casUsersyncinfo = cerCasUsersyncinfoService.findUserById(byId.getId());
        if (!Objects.isNull(casUsersyncinfo)) {
            // 标记数据已经同步
            casUsersyncinfo.setIsInitSysuser(1);
            casUsersyncinfo.setSysuserid(String.valueOf(sysUser.getId()));
            cerCasUsersyncinfoService.updateByPrimaryKeySelective(casUsersyncinfo);
        }

        // 数据写入完成后,需要删除当前临时表中的数据
        zjcodeSysUserTmpService.deleteById(byId.getId());

        Map<String, Object> result = new HashMap<>();
        result.put("id", record.getId());
        return JsonObj.success(result);
    }

    private static SysUser getSysUser(ZjcodeSysUserTmp byId, long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setId(userId);
        sysUser.setUsername(byId.getUsername());
        sysUser.setPassword(byId.getPassword());
        sysUser.setEmail(byId.getEmail());
        sysUser.setMobile(byId.getMobile());
        sysUser.setPrefix(byId.getPrefix());
        sysUser.setNickname(byId.getNickname());
        sysUser.setPhone(byId.getPhone());
        sysUser.setProvinceRegioncode(byId.getProvinceRegioncode());
        sysUser.setCityRegioncode(byId.getCityRegioncode());
        sysUser.setAddress(byId.getAddress());
        sysUser.setProfile(byId.getProfile());
        sysUser.setAvatar(byId.getAvatar());
        sysUser.setOrgId(byId.getOrgId());
        sysUser.setStatus(byId.getStatus());
        sysUser.setNotifyMessage(byId.getNotifyMessage());
        sysUser.setNotifyTodo(byId.getNotifyTodo());
        sysUser.setCreateTime(byId.getCreateTime());
        sysUser.setUpdateTime(byId.getUpdateTime());
        sysUser.setTenantCode(byId.getTenantCode());
        sysUser.setAuthorizationCode(byId.getAuthorizationCode());
        return sysUser;
    }

    /**
     * 更新用户
     *
     * @return
     */
    @PostMapping("updateSysUser")
    public JsonObj updateSysUser(@RequestBody PageData pageData) {
        String data = (String) pageData.get("data");
        ZjcodeSysUserTmp record = JSONObject.parseObject(data, ZjcodeSysUserTmp.class);
        zjcodeSysUserTmpService.updateSysUser(record);
        Map<String, Object> result = new HashMap<>();
        result.put("id", record.getId());
        return JsonObj.success(result);
    }


}
